<script setup lang="ts">
import { ref, computed } from 'vue';
import { ElDialog, ElButton, ElMessage, ElDivider } from 'element-plus';
import { FileText, Trash2 } from '@vben/icons';
import { uploadExamQuestionsApi } from "#/api/manage/question-bank";
import Download from "#/components/download.vue";
import { autoDownloadFromResult } from "#/utils/download";
import { $t } from '@vben/locales';

defineOptions({ name: 'UploadModal' });

const emit = defineEmits(['refresh']);

// Modal state
const visible = ref(false);
const selectedFile = ref<File | null>(null);
const uploading = ref(false);

// Constants
const obs = {
  Key: `import/${$t('questionBank.templateFileName')}`,
};

const blobConfig = {
  type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
};

// Event handlers
const handleFileChange = (file: any) => {
  console.log('文件改变:', file);
  if (file && file.raw) {
    const rawFile = file.raw as File;
    
    // 验证文件类型
    const allowedTypes = [
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', // .xlsx
      'application/vnd.ms-excel' // .xls
    ];
    
    if (!allowedTypes.includes(rawFile.type) && !rawFile.name.match(/\.(xlsx|xls)$/i)) {
      ElMessage.error($t('common.xlsxFileFormatTxt'));
      return;
    }
    
    console.log('文件选择成功:', rawFile.name, rawFile.size);
    selectedFile.value = rawFile;
  }
};

const handleFileSelect = (file: File) => {
  // 验证文件类型
  const allowedTypes = [
    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', // .xlsx
    'application/vnd.ms-excel' // .xls
  ];
  
  if (!allowedTypes.includes(file.type) && !file.name.match(/\.(xlsx|xls)$/i)) {
    ElMessage.error($t('common.xlsxFileFormatTxt'));
    return false;
  }
  
  console.log('文件选择成功:', file.name, file.size);
  selectedFile.value = file;
  return false; // 阻止自动上传，但允许文件选择
};

const handleUpload = async () => {
  if (!selectedFile.value) {
    ElMessage.warning($t('common.selectPhTxt', [$t('common.uploadFileTxt')]));
    return;
  }
  
  uploading.value = true;
  
  try {
    console.log('开始上传文件:', selectedFile.value.name);
    const formData = new FormData();
    formData.append('file', selectedFile.value);
    
    const result = await uploadExamQuestionsApi(formData);
    console.log('上传结果:', result);
    
    // 如果结果是一个URL，则自动下载
    const hasDownload = await autoDownloadFromResult(result);
    if (hasDownload) {
      ElMessage.success($t('questionBank.uploadSuccessWithDownload'));
    } else {
      ElMessage.success($t('common.uploadSuccessTxt'));
    }
    
    emit('refresh');
    selectedFile.value = null; // 清空选中的文件
    visible.value = false;
  } catch (error) {
    console.error('上传失败:', error);
    ElMessage.error($t('questionBank.uploadFailedWithError', [(error as any)?.message || $t('questionBank.unknownError')]));
  } finally {
    uploading.value = false;
  }
};

const handleRemoveFile = () => {
  selectedFile.value = null;
};

const formatFileSize = (bytes: number) => {
  if (bytes === 0) return '0 Bytes';
  const k = 1024;
  const sizes = ['Bytes', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
};



// Computed properties
const dialogTitle = computed(() => {
  return selectedFile.value ? $t('questionBank.uploadFileWithName', [selectedFile.value.name]) : $t('questionBank.uploadFile');
});

const handleClose = () => {
  visible.value = false;
  selectedFile.value = null;
};

const open = () => {
  visible.value = true;
};

defineExpose({
  open,
});
</script>

<template>
  <ElDialog v-model="visible" :title="dialogTitle" width="500px" :close-on-click-modal="false" @close="handleClose">
    <div class="upload-content">
      <div class="text-center mb-6">
        <p class="text-gray-600 mb-4">{{ $t('questionBank.noTemplate') }}</p>
        <Download 
          class="mb-4" 
          :downloadName="$t('questionBank.downloadTemplate')" 
          :plain="true" 
          :obs="obs" 
          :blobConfig="blobConfig" 
          type="primary"
        />
      </div>
      
      <!-- <ElDivider>{{ $t('questionBank.or') }}</ElDivider> -->
      
      <div class="text-center">
        <!-- File upload area when no file selected -->
        <el-upload 
          v-if="!selectedFile"
          action="#" 
          :on-change="handleFileChange"
          accept=".xlsx, .xls" 
          :auto-upload="false"
          :show-file-list="false"
          drag
          class="w-full"
        >
          <div class="py-8">
            <div class="text-primary text-4xl mb-4">📁</div>
            <div class="text-lg mb-2">{{ $t('questionBank.clickOrDragToUpload') }}</div>
            <div class="text-gray-500 text-sm">{{ $t('questionBank.supportFileFormat') }}</div>
          </div>
        </el-upload>
        
        <!-- Selected file display -->
        <div v-else class="selected-file-container p-4 border border-gray-300 rounded-lg bg-gray-50">
          <div class="flex items-center justify-between">
            <div class="flex items-center">
              <FileText class="w-6 h-6 text-primary mr-3" />
              <div class="text-left">
                <div class="text-sm font-medium text-gray-900">{{ selectedFile.name }}</div>
                <div class="text-xs text-gray-500">{{ formatFileSize(selectedFile.size) }}</div>
              </div>
            </div>
            <ElButton 
              type="danger" 
              :icon="Trash2" 
              circle 
              link
              size="small"
              @click="handleRemoveFile"
            />
          </div>
        </div>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <ElButton @click="handleClose">{{ $t('questionBank.cancel') }}</ElButton>
        <ElButton 
          type="primary" 
          :disabled="!selectedFile || uploading"
          :loading="uploading"
          @click="handleUpload"
        >
          {{ uploading ? $t('questionBank.uploading') : $t('questionBank.confirmUpload') }}
        </ElButton>
      </div>
    </template>
  </ElDialog>
</template>

<style lang="scss" scoped>
.upload-content {
  padding: 20px 0;
}

:deep(.el-upload-dragger) {
  border: 2px dashed #d9d9d9;
  border-radius: 8px;
  width: 100%;
  height: auto;
  position: relative;
  overflow: hidden;
  text-align: center;
  background-color: #fafafa;
  transition: border-color 0.3s;
}

:deep(.el-upload-dragger:hover) {
  border-color: #409eff;
}

.text-primary {
  color: #409eff;
}
</style> 
